<template>
  <div class="upload-file">
    <el-upload
        class="avatar-uploader"
        action="/api/sysUser/uploadAvatar"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        :data="{ id: userId }"
        name="avatar">
      <img v-if="modelValue" :src="modelValue" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
  </div>
</template>

<script>

export default {
  name: "FileUpload",
  props: {
    modelValue: {
      type: String,
      default: ''
    },
    userId: {
      type: Number,
      required: true
    }
  },
  emits: ['update:modelValue'],
  methods: {
    // 处理头像上传成功
    handleAvatarSuccess(res) {
      if (res.code === 200) {
        this.$emit('update:modelValue', res.data);
        this.$message.success('头像上传成功');
      } else {
        this.$message.error(res.msg || '头像上传失败');
      }
    },

    // 头像上传前检查
    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('上传头像图片只能是图片格式!');
        return false;
      }

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
        return false;
      }

      return true;
    },
  }
}
</script>

<style scoped>
.avatar-uploader {
  margin-top: 10px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}
</style>
